package com.github.byakkili.bim.protocol.json2protobuf;

import com.github.byakkili.bim.core.BimContext;
import com.github.byakkili.bim.core.BimSession;
import com.github.byakkili.bim.core.handler.command.CommandFrame;
import com.github.byakkili.bim.core.handler.command.CommandProcessor;
import com.github.byakkili.bim.core.support.util.CommandProcessorUtils;
import com.github.byakkili.bim.protocol.ProtoBufHelper;
import com.google.protobuf.Message;
import io.netty.handler.codec.MessageToMessageCodec;

import java.util.Map;

/**
 * @author Guannian Li
 */
public abstract class BaseJson2protoBufCodec<T> extends MessageToMessageCodec<T, CommandFrame<Message>> {

    protected CommandFrame convertCommandFrame(BimSession session, int command, String jsonStr) {
        BimContext context = session.getContext();
        Map<Integer, CommandProcessor> commandHandlers = context.getConfig().getCommandProcessors();

        CommandProcessor commandHandler = commandHandlers.get(command);
        if (commandHandler == null) {
            return new CommandFrame<>(command, null);
        }
        Class<Message> msgClass = CommandProcessorUtils.getMsgClass(commandHandler);
        Message message = ProtoBufHelper.deserializeJson(jsonStr, msgClass);
        return new CommandFrame<>(command, message);
    }
}
